package cn.chenxiejia;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: T7
 * @Description: volatile和synchronized的区别, 后者更快
 * @Author: chenxiejia
 * @Date: 2022/2/8 9:03
 */
public class T7 {
    volatile static int num = 0;
    static CountDownLatch latch = new CountDownLatch(100);
    //volatile线程可见
    static volatile AtomicInteger a = new AtomicInteger();

    public static void main(String[] args) {
        var s = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            T7 tt = new T7();
            new Thread(T7::ss, "T" + i).start();
        }
        //new Thread(T7::s1).start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis() - s);
    }

    static void s1() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a);
    }

    synchronized static void ss1() {
        for (int i = 0; i < 1000; i++) {
            num++;
        }
        latch.countDown();
    }

    static void ss() {
        for (int i = 0; i < 1000; i++) {
            a.incrementAndGet();
        }
        latch.countDown();
    }


}
